package com.it360.hms_js;


import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.data.distributed.common.*;
import ohos.data.distributed.user.SingleKvStore;
import ohos.rpc.*;
import ohos.utils.zson.ZSONObject;

import java.util.*;

public class BoardServiceAbility extends Ability {

    private KvManagerConfig config;
    private KvManager kvManager;
    private String storeID = "board";
    private SingleKvStore singleKvStore;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        //初始化manager
        config = new KvManagerConfig(this);
        kvManager = KvManagerFactory.getInstance().createKvManager(config);

        //创建数据库
        Options options = new Options();
        options.setCreateIfMissing(true).setEncrypt(false).setKvStoreType(KvStoreType.SINGLE_VERSION);
        singleKvStore = kvManager.getKvStore(options, storeID);

    }


    private static final String TAG = "BoardServiceAbility";

    private MyRemote remote = new MyRemote();

    @Override
    protected IRemoteObject onConnect(Intent intent) {
        super.onConnect(intent);
        return remote.asObject();
    }

    class MyRemote extends RemoteObject implements IRemoteBroker {


        private static final int ERROR = -1;
        private static final int SUCCESS = 0;
        private static final int SUBSCRIBE = 3000;
        private static final int UNSUBSCRIBE = 3001;
        private static final int OPEDRECTION = 2000;
        private static final int OPEN_DEVICE = 4000;
        private static final int GHE_DEVICE = 1001;

        private Set<IRemoteObject> remoteObjectHandlers = new HashSet<IRemoteObject>();

        MyRemote() {
            super("MyService_MyRemote");
        }

        @Override
        public boolean onRemoteRequest(int code, MessageParcel data, MessageParcel reply, MessageOption option) throws RemoteException {

            switch (code) {
                case OPEDRECTION:{
                    List deviceList= DeviceUtils.getDevice();
                    String zsonStr=data.readString();
                    BoardRequestParam param= ZSONObject.stringToClass(zsonStr,BoardRequestParam.class);
                    Map<String, Object> zsonResult = new HashMap<String, Object>();
                    System.out.println("-------Board OPEDRECTION-------");
                    zsonResult.put("data", param.getPoint());
                    try {
                        singleKvStore.putString("point", param.getPoint());
                    } catch (KvStoreException e) {
                        e.printStackTrace();
                    }
                    zsonResult.put("code", SUCCESS);
                    reply.writeString(ZSONObject.toZSONString(zsonResult));
                    break;
                }

                //获取设备
                case GHE_DEVICE:{
                    Map<String, Object> zsonResult = new HashMap<String, Object>();
                    List deviceList= DeviceUtils.getDevice();
                    zsonResult.put("data",deviceList);
                    zsonResult.put("code", SUCCESS);
                    reply.writeString(ZSONObject.toZSONString(zsonResult));
                    System.out.println("+++++++"+deviceList+"++++++++");
                    break;
                }
                // 开启订阅，保存对端的remoteHandler，用于上报数据
                case SUBSCRIBE: {
                    remoteObjectHandlers.add(data.readRemoteObject());
                    startNotify();
                    Map<String, Object> zsonResult = new HashMap<String, Object>();
                    zsonResult.put("code", SUCCESS);
                    reply.writeString(ZSONObject.toZSONString(zsonResult));
                    break;
                }
                // 取消订阅，置空对端的remoteHandler
                case UNSUBSCRIBE: {
                    remoteObjectHandlers.remove(data.readRemoteObject());
                    Map<String, Object> zsonResult = new HashMap<String, Object>();
                    zsonResult.put("code", SUCCESS);
                    reply.writeString(ZSONObject.toZSONString(zsonResult));
                    break;
                }
                case OPEN_DEVICE:{
                    System.out.println("+++++++OPEN_DEVICE++++++++");
                    Map<String, Object> zsonResult = new HashMap<String, Object>();
                    String deviceId= DeviceUtils.getDeviceId();
                    Intent intent=  DeviceUtils.getAbilityIntent(deviceId,"com.cangjie.jsabilitydemo.GameAbility");
                    startAbility(intent);
                    zsonResult.put("code", SUCCESS);
                    zsonResult.put("data",intent);

                    reply.writeString(ZSONObject.toZSONString(zsonResult));
                    break;
                }
                default: {
                    reply.writeString("service not defined");
                    return false;
                }
            }
            return true;
        }

        public void startNotify() {
            new Thread(() -> {
                while (true) {
                    try {
                        Thread.sleep(30);
                        testReportEvent();
                    } catch (RemoteException | InterruptedException e) {
                        break;
                    }
                }
            }).start();
        }

        private void testReportEvent() throws RemoteException {
            String points = "";
            try {
                points = singleKvStore.getString("point");
                singleKvStore.delete("point");
            } catch (KvStoreException e) {
                e.printStackTrace();
            }
            MessageParcel data = MessageParcel.obtain();
            MessageParcel reply = MessageParcel.obtain();
            MessageOption option = new MessageOption();
            Map<String, Object> zsonEvent = new HashMap<String, Object>();

            zsonEvent.put("point", points);
            data.writeString(ZSONObject.toZSONString(zsonEvent));

            for (IRemoteObject item : remoteObjectHandlers) {
                item.sendRequest(100, data, reply, option);
            }

            reply.reclaim();
            data.reclaim();
        }

        @Override
        public IRemoteObject asObject() {
            return this;
        }
    }
}